package com.moon.filter;

import com.moon.utils.CurrentUserContextHolder;
import com.moon.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");
        if (!StringUtils.hasLength(token)) {
            log.info("没有token");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
            CurrentUserContextHolder.set(JwtUtils.getLoginInfoFromToken(claims));
        } catch (Exception e) {
            log.info("token解析失败");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//
//    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 无论成功、失败、异常都清理 ThreadLocal，放到afterCompletion中，避免内存泄漏
        CurrentUserContextHolder.clear();
    }
}
